package com.example.fasttransfer.tasks;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
public class FileCleanerTask {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.expiration-time}")
    private int expirationTime;

    // 每分钟执行一次
    @Scheduled(fixedDelay = 60 * 1000)
    public void cleanExpiredFiles() {
        File uploadDirFile = new File(uploadDir);
        File[] files = uploadDirFile.listFiles();

        if (files != null) {
            long currentTime = System.currentTimeMillis();
            for (File file : files) {
                // 如果文件未在规定的时间内被下载，删除它
                if (currentTime - file.lastModified() > expirationTime * 60 * 1000) {
                    file.delete();
                    System.out.println("Deleted expired file: " + file.getName());
                }
            }
        }
    }
}
